<?php

namespace Trawind\Extension\Commands;

use Illuminate\Console\Command;
use Trawind\Basics\Traits\Console\SingleTenantConsole;
use Trawind\Extension\Models\Deploy\BusinessType;

class SystemBusinessTypeCommand extends Command
{

    use SingleTenantConsole;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:business-type';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fill in the fields of all data tables';


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function exec()
    {
        $eloquents = $this->getAllEloquent();
        foreach ($eloquents as $eloquent) {
            $model = app(app($eloquent)->model());
            if (!is_null($businessTypeId = $model->businessType)) {
                if ($data = BusinessType::find($businessTypeId)) {
                    $data->fill([
                        'table_name' => $model->getTable(),
                        'local_class' => $eloquent
                    ]);
                    $data->save();
                    $this->info($eloquent.' 已更新...');
                }
            }
        }
        $this->comment("Filling is complete!");
        return 1;
    }


    protected function getAllEloquent()
    {
        $fqcns = [];

        $allFiles = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(app('path').'/Repositories'));
        $phpFiles = new \RegexIterator($allFiles, '/\.php$/');
        foreach ($phpFiles as $phpFile) {
            $content = file_get_contents($phpFile->getRealPath());
            $tokens = token_get_all($content);
            $namespace = '';
            for ($index = 0; isset($tokens[$index]); $index++) {
                if (!isset($tokens[$index][0])) {
                    continue;
                }
                if (T_NAMESPACE === $tokens[$index][0]) {
                    $index += 2;
                    while (isset($tokens[$index]) && is_array($tokens[$index])) {
                        $namespace .= $tokens[$index++][1];
                    }
                }
                if (T_CLASS === $tokens[$index][0] && T_WHITESPACE === $tokens[$index + 1][0] && T_STRING === $tokens[$index + 2][0]) {
                    $index += 2;
                    $fqcns[] = $namespace.'\\'.$tokens[$index][1];
                    break;
                }
            }
        }
        return $fqcns;
    }


    protected function getTenantId()
    {
        $tenantId = config('app.env') == 'develop' ? '100000-d' : '100000-p';
        return $this->option('tenant_id') ?? $tenantId;
    }

}
